package com.cqie.exception;



import com.cqie.constant.ResultCodeEnum;
import com.cqie.util.ResultTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

/**
 * 全局校验处理器
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 校验异常处理
     * @param e
     * @return
     * @throws SpecialException
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<ResultTemplate<String>> handleValidationExceptions(MethodArgumentNotValidException e)  {
        String message = e.getBindingResult().getFieldErrors()
                .stream()
                .map(ex -> ex.getDefaultMessage() )
                .findFirst()
                .orElse("参数验证失败");

        // 返回一个 ResponseEntity，而不是抛出异常
        ResultTemplate<String> response = ResultTemplate.Failed(ResultCodeEnum.SYSTEM_EXCEPTION.getCode(), message);
        return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST);
    }

    /**
     * 自定义异常返回结果处理
     * @param e
     * @return
     */
    @ExceptionHandler(SpecialException.class)
    public ResponseEntity<ResultTemplate<String>> handleYiChangSJException(SpecialException e) {
        ResultTemplate<String> response = ResultTemplate.Failed(e.getCode(), e.getMessage());
        return new ResponseEntity<>(response, HttpStatus.OK);
    }
}